import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {PageDecorationService} from '../../../page-decoration.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {moveItemInArray} from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-decoration-loop-images',
  templateUrl: './loop-images.component.html',
  styleUrls: ['./loop-images.component.scss']
})
export class LoopImagesComponent implements OnInit {
  @Input() componentData: any; // 原始数据
  @Output() save = new EventEmitter(); // 保存修改
  @Output() closeComponent = new EventEmitter(); // 关闭
  componentNameDisabled = false; // 组件名输入框禁用状态

  linkList = [];

  constructor(
    private pageDecorationService: PageDecorationService,
    private nzMessageService: NzMessageService
  ) {
  }

  ngOnInit(): void {
    this.componentNameDisabled = !!this.componentData?.name;
    this.pageDecorationService.getLinkList().then((res: any) => {
      if (res.code === 0) {
        this.linkList = res.data.records;
      }
    });
  }

  linkToRemark(link: any) {
    const item = this.linkList.filter((i: any) => i.key === link);
    if (item.length) {
      return item[0]['remarks'];
    }
    return '';
  }

  drop(event: any) {
    moveItemInArray(this.componentData.content, event.previousIndex, event.currentIndex);
  }

  addItem() {
    if (this.componentData.content.length >= 10) {
      this.nzMessageService.error('图片不能超过10个');
      return;
    }
    this.componentData.content.push({image: '', link: '', params: ''});
  }

  removeItem(index: number) {
    this.componentData.content.splice(index, 1);
  }

  saveBtn() {
    if (!this.componentData.content.length) {
      this.nzMessageService.error('至少需要一条数据');
      return;
    }
    this.save.emit(this.componentData);
  }
}
